package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.album.mapper.*;
import com.atguigu.tingshu.album.service.BaseCategoryService;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.service.KafkaService;
import com.atguigu.tingshu.model.album.*;
import com.atguigu.tingshu.vo.album.AlbumAttributeValueVo;
import com.atguigu.tingshu.vo.album.AlbumInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@SuppressWarnings({"all"})
public class BaseCategoryServiceImpl extends ServiceImpl<BaseCategory1Mapper, BaseCategory1> implements BaseCategoryService {

    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;

    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;

    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;

    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;

	@Autowired
	private BaseAttributeMapper baseAttributeMapper;

	@Autowired
	private AlbumInfoMapper albumInfoMapper;

	@Autowired
	private AlbumAttributeValueMapper albumAttributeValueMapper;

	@Autowired
	private AlbumStatMapper albumStatMapper;

	@Autowired
	private KafkaService kafkaService;

    @Override
    public List<JSONObject> getBaseCategoryList() {
		//1.创建目标集合对象
		List<JSONObject> allList = new ArrayList<>();
		//2.查询分类视图得到所有分类数据 共计401条记录
		List<BaseCategoryView> allCategoryList = baseCategoryViewMapper.selectList(null);
		//3.处理一级分类，对所有分类数据根据-根据一级分类ID分组
		//3.1 采用Stream流进行集合分组，得到Map集合，Map中key:1级分类ID Map中Value：1级分类集合
		Map<Long, List<BaseCategoryView>> category1Map =
				allCategoryList.stream()
						.collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));
		if (CollectionUtil.isNotEmpty(category1Map)) {
			for (Map.Entry<Long, List<BaseCategoryView>> entry1 : category1Map.entrySet()) {
				//每遍历一次处理一个一级分类
				//3.2 获取一级分类ID 以及 名称
				Long category1Id = entry1.getKey();
				String category1Name = entry1.getValue().get(0).getCategory1Name();
				//3.3 构建一级分类JSON对象
				JSONObject jsonObject1 = new JSONObject();
				jsonObject1.put("categoryId", category1Id);
				jsonObject1.put("categoryName", category1Name);
				//4.在某个一级分类内，处理二级分类，对一级分类集合根据二级分类ID分组
				Map<Long, List<BaseCategoryView>> category2Map = entry1.getValue().stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
				//4.2 对某个一级分类集合按照二级分类ID进行分组 得到二级分类Map Map-key 二级分类ID Map-Value 二级分类集合
				if (CollectionUtil.isNotEmpty(category2Map)) {
					List<JSONObject> jsonObject2List = new ArrayList<>();
					for (Map.Entry<Long, List<BaseCategoryView>> entry2 : category2Map.entrySet()) {
						//4.3 获取二级分类ID 以及 名称
						Long category2Id = entry2.getKey();
						String category2Name = entry2.getValue().get(0).getCategory2Name();
						//4.4 遍历构建二级分类JSON对象 将二级分类对象加入到集合中
						JSONObject jsonObject2 = new JSONObject();
						jsonObject2.put("categoryId", category2Id);
						jsonObject2.put("categoryName", category2Name);
						//5.TODO 在某个二级分类内，处理三级分类
						//5.1 遍历二级分类Map中Value
						List<JSONObject> jsonObject3List = new ArrayList<>();
						for (BaseCategoryView baseCategoryView : entry2.getValue()) {
							//5.2 获取三级分类ID跟名称
							Long category3Id = baseCategoryView.getCategory3Id();
							String category3Name = baseCategoryView.getCategory3Name();
							//5.3 构建三级分类JSON对象
							JSONObject jsonObject3 = new JSONObject();
							jsonObject3.put("categoryId", category3Id);
							jsonObject3.put("categoryName", category3Name);
							jsonObject3List.add(jsonObject3);
						}
						//5.4 将构建三级分类集合放入二级分类对象中"categoryChild"属性中
						jsonObject2.put("categoryChild", jsonObject3List);
						jsonObject2List.add(jsonObject2);
					}
					//4.5 将二级分类集合放入一级分类对象中"categoryChild"中
					jsonObject1.put("categoryChild", jsonObject2List);
				}
				//3.4 将一级分类对象加入到所有目标集合对象中
				allList.add(jsonObject1);
			}
		}
		return allList;
    }


	@Override
	public List<BaseAttribute> selectAttribute(Long category1Id) {
		return baseAttributeMapper.selectAttribute(category1Id);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)  // 由于默认事务捕捉的只有 RuntimeException 无法捕获，SQL异常，所以得扩大
	public void saveAlbumInfo(AlbumInfoVo albumInfoVo,Long userId) {

		AlbumInfo albumInfo = BeanUtil.copyProperties(albumInfoVo, AlbumInfo.class);
		albumInfo.setUserId(userId);
		albumInfo.setIncludeTrackCount(0);
		albumInfo.setIsFinished("0");
		albumInfo.setTracksForFree(5);
		albumInfo.setStatus(SystemConstant.ALBUM_STATUS_PASS);

		albumInfoMapper.insert(albumInfo);
		Long albumId = albumInfo.getId();


		//2.保存专辑标签关系
		//2.1 将提交专辑标签关系VO集合转为PO集合
//		List<AlbumAttributeValueVo> albumAttributeValueVoList = albumInfoVo.getAlbumAttributeValueVoList();
//		if (CollectionUtil.isNotEmpty(albumAttributeValueVoList)) {
//			//2.2 关联专辑ID批量保存专辑标签关系
//			for (AlbumAttributeValueVo albumAttributeValueVo : albumAttributeValueVoList) {
//				AlbumAttributeValue albumAttributeValue = BeanUtil.copyProperties(albumAttributeValueVo, AlbumAttributeValue.class);
//				albumAttributeValue.setAlbumId(albumId);
//				albumAttributeValueMapper.insert(albumAttributeValue);
//			}
//		}

		List<AlbumAttributeValueVo> albumAttributeValueVoList = albumInfoVo.getAlbumAttributeValueVoList();

		if(CollectionUtil.isNotEmpty(albumAttributeValueVoList)){

			List<AlbumAttributeValue> albumAttributeValueList = albumAttributeValueVoList.stream().map(albumAttributeValueVo -> {

				AlbumAttributeValue albumAttributeValue = BeanUtil.copyProperties(albumAttributeValueVo, AlbumAttributeValue.class);
				albumAttributeValue.setAlbumId(albumId);
				System.out.println(albumAttributeValue);
				return albumAttributeValue;

			}).collect(Collectors.toList());
			albumAttributeValueMapper.insertBatch(albumAttributeValueList);
		}

		//3.保存专辑统计信息（4条）
		this.saveAlbumStat(albumId, SystemConstant.ALBUM_STAT_PLAY, 0);
		this.saveAlbumStat(albumId, SystemConstant.ALBUM_STAT_SUBSCRIBE, 0);
		this.saveAlbumStat(albumId, SystemConstant.ALBUM_STAT_BUY, 0);
		this.saveAlbumStat(albumId, SystemConstant.ALBUM_STAT_COMMENT, 0);


		//5.审核通过后发送上架专辑消息到Kafka
		if ("1".equals(albumInfo.getIsOpen())) {
			kafkaService.sendMessage(KafkaConstant.QUEUE_ALBUM_UPPER,albumId.toString());
		}
	}

	/**
	 * 保存专辑统计信息
	 * @param albumId 专辑ID
	 * @param statType 统计类型
	 * @param statNum 统计数量
	 */
	public void saveAlbumStat(Long albumId, String statType, int statNum) {
		AlbumStat albumStat = new AlbumStat();
		albumStat.setAlbumId(albumId);
		albumStat.setStatType(statType);
		albumStat.setStatNum(statNum);
		albumStatMapper.insert(albumStat);
	}


	@Override
	public BaseCategoryView getCategoryView(Long category3Id) {
		return baseCategoryViewMapper.selectById(category3Id);
	}


	@Override
	public List<BaseCategory3> findTopBaseCategory3(Long category1Id) {
		// 根据一级分类查找二级分类
		QueryWrapper<BaseCategory2> baseCategory2QueryWrapper = new QueryWrapper<>();
		baseCategory2QueryWrapper.eq("category1_id",category1Id);
		List<BaseCategory2> baseCategory2s = baseCategory2Mapper.selectList(baseCategory2QueryWrapper);
		// 根据二级查找三级
		List<Long> category2Id = baseCategory2s.stream().map(baseCategory2 -> baseCategory2.getId()).collect(Collectors.toList());
		// 查找三级
		QueryWrapper<BaseCategory3> baseCategory3QueryWrapper = new QueryWrapper<>();
		baseCategory3QueryWrapper.in("category2_id",category2Id);
		baseCategory3QueryWrapper.eq("is_top",1);
		baseCategory3QueryWrapper.orderByAsc("order_num");
		baseCategory3QueryWrapper.last("limit 7");

		return baseCategory3Mapper.selectList(baseCategory3QueryWrapper);
	}

	@Override
	public JSONObject getBaseCategoryListByCategory1Id(Long category1Id) {

		JSONObject jsonObject = new JSONObject();

		// 根据一级分类id查询
		List<BaseCategoryView> baseCategoryViews = baseCategoryViewMapper.selectList(new QueryWrapper<BaseCategoryView>().eq("category1_id", category1Id));

		// 封装第一层
		jsonObject.put("categoryId",baseCategoryViews.get(0).getCategory1Id());
		jsonObject.put("categoryName",baseCategoryViews.get(0).getCategory1Name());


		Map<Long, List<BaseCategoryView>> category2Map = baseCategoryViews.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));

		List<JSONObject> jsonObject2List = new ArrayList<>();
		for (Map.Entry<Long, List<BaseCategoryView>> entry2 : category2Map.entrySet()) {

			JSONObject jsonObject2 = new JSONObject();
			jsonObject2.put("categoryId",entry2.getKey());
			jsonObject2.put("categoryName",entry2.getValue().get(0).getCategory2Name());

			ArrayList<JSONObject> jsonObject3List = new ArrayList<>();
			for (BaseCategoryView baseCategoryView : entry2.getValue()) {
				JSONObject jsonObject3 = new JSONObject();
				jsonObject3.put("categoryId",baseCategoryView.getCategory3Id());
				jsonObject3.put("categoryName",baseCategoryView.getCategory3Name());
				jsonObject3List.add(jsonObject3);
			}
			jsonObject2.put("categoryChild",jsonObject3List);

			jsonObject2List.add(jsonObject2);
		}
		jsonObject.put("categoryChild",jsonObject2List);

		return jsonObject;
	}


}





























